package com.chc.web.sys_notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chc.utils.Msg;
import com.chc.web.sys_notice.entity.SysNotice;
import com.chc.web.sys_notice.entity.SysNoticeParm;
import com.chc.web.sys_notice.service.SysNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/01/21/15:14
 * @Description:
 */
@RestController
@RequestMapping("api/sysNotice")
public class SysNoticeController {
    @Autowired
    private SysNoticeService sysNoticeService;

    /**
     * 查询列表
     * */
    @GetMapping("/list")
    public Msg getList(SysNoticeParm parm){
        //构造条件
        QueryWrapper<SysNotice> query = new QueryWrapper();
        query.lambda().like(SysNotice::getTitle,parm.getTitle()).orderByDesc(SysNotice::getCreateTime);
        //构造分页对象
        IPage<SysNotice> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        IPage<SysNotice> list = sysNoticeService.page(page, query);
        return Msg.success("查询成功",list);
    }

    /**
     * 新增
     * */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:noticeList:add')")
    public Msg add(@RequestBody SysNotice sysNotice){
        sysNotice.setCreateTime(new Date());
        boolean save = sysNoticeService.save(sysNotice);
        if(save){
            return Msg.success("新增成功!");
        }
        return Msg.error("新增失败!");
    }

    /**
     * 编辑
     * */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:noticeList:edit')")
    public Msg edit(@RequestBody SysNotice sysNotice){
        boolean b = sysNoticeService.updateById(sysNotice);
        if(b){
            return Msg.success("编辑成功!");
        }
        return Msg.error("编辑失败!");
    }

    /**
     * 删除
     * */
    @DeleteMapping("/{noticeId}")
    @PreAuthorize("hasAuthority('sys:noticeList:delete')")
    public Msg delete(@PathVariable("noticeId") Long noticeId){
        boolean b = sysNoticeService.removeById(noticeId);
        if(b){
            return Msg.success("删除成功!");
        }
        return Msg.error("删除失败!");
    }
}
